package com.rojored.net 
{

import com.rojored.net.imageUploaderClasses.ImageFile;
import com.rojored.net.imageUploaderClasses.ImageMimeType;
import com.rojored.net.imageUploaderClasses.ImageUploaderEvent;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.geom.Rectangle;
import flash.net.FileFilter;
import flash.net.FileReference;
import flash.utils.getQualifiedClassName;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.utils.ObjectUtil;

//--------------------------------------
//   Events 
//--------------------------------------

/**
 *  Dispatched when the upload has finished and the new <code>ImageFile</code>
 *  has been packed and is available.
 */
[Event(name="imageUploadComplete", type="com.rojored.net.imageUploaderClasses.ImageUploaderEvent")]

/**
 *  Dispatched when the upload has been canceled through the file-browsing
 *  dialog by the user.
 */
[Event(name="cancel")]

/**
 *  Uploads an image file from the filesystem into the flash player.
 *
 *  @author gabriel montagné láscaris-comneno gabriel@rojored.com 
 */
public class ImageUploader extends EventDispatcher 
{

    //--------------------------------------------------------------------------
    //
    //  Constructor
    //
    //--------------------------------------------------------------------------

    /**
     *  Constructor
     */
    public function ImageUploader() 
    {
        super();
    }

    //--------------------------------------------------------------------------
    //
    //  Variables 
    //
    //--------------------------------------------------------------------------

    /**
     *  @private
     */
    private var currentImage:ImageFile;

    /**
     *  @private
     *  image file reference 
     */
    private var imageFile:FileReference;

    /**
     *  @private
     *  Internal loader, used to load the bytes of the image upload into a
     *  bitmap that flash can understand.
     */
    private var imageLoader:Loader;

    /**
     *  @private
     */
    private var logger:ILogger =
        Log.getLogger(getQualifiedClassName(this).replace(/\W+/g, "."));

    //--------------------------------------------------------------------------
    //
    //  Methods 
    //
    //--------------------------------------------------------------------------

    /**
     *  Opens up a browser browse dialog.  This can only be called from a user
     *  gesture (mouse click, etc.)
     */
    public function browse():void
    {
        currentImage = null;
        if (!imageFile)
        {
            imageFile = new FileReference();
            imageFile.addEventListener(Event.SELECT, imageFile_selectHandler);
            imageFile.addEventListener(Event.COMPLETE,
                imageFile_completeHandler);
            imageFile.addEventListener(Event.CANCEL, imageFile_cancelHandler);
        }
        imageFile.browse([ new FileFilter( "Image", "*.jpg;*.png") ]);
    }

    //--------------------------------------------------------------------------
    //
    //  Event handlers 
    //
    //--------------------------------------------------------------------------

    /**
     *  @private
     */
    private function imageFile_selectHandler(event:Event):void
    {
        imageFile.load();
    }

    /**
     *  @private
     */
    private function imageFile_cancelHandler(event:Event):void
    {
        dispatchEvent(event);
    }

    /**
     *  @private
     */
    private function imageFile_completeHandler(event:Event):void
    {
        // TODO: mime-type by extension is not good.
        currentImage = new ImageFile(
            imageFile.name,
            imageFile.data,
            /\.png$/.test(imageFile.name) ? 
                ImageMimeType.MIME_TYPE_PNG : ImageMimeType.MIME_TYPE_JPG
        );

        if (!imageLoader)
        {
            imageLoader = new Loader();
            var loaderInfo:LoaderInfo = imageLoader.contentLoaderInfo;
            loaderInfo.addEventListener(
                Event.COMPLETE,
                loaderInfo_completeHandler
            );
        }
        imageLoader.loadBytes(currentImage.rawBytes);
    }

    /**
     *  @private
     */
    private function loaderInfo_completeHandler(event:Event):void
    {
        currentImage.bitmapData = Bitmap(imageLoader.content).bitmapData;
        currentImage.dimensions = currentImage.bitmapData.rect;
        dispatchEvent(
            new ImageUploaderEvent(
                ImageUploaderEvent.IMAGE_UPLOAD_COMPLETE,
                currentImage
            )
        );
        currentImage = null;
    }
}
}
